import {
    baseUrl,
    official_appid,
} from '@/config/index.js'

const weixin_getCode = () => {
    return new Promise((resolve, reject) => {
        uni.login({
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

const getUrlParam = (name) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const r = window.location.search.substr(1).match(reg)
    if (r != null) {
        return unescape(r[2])
    }
    return null
}

const Wechat_webpage_authorization_getCode = () => {
    const code = getUrlParam('code')
    const local = `${baseUrl}/pages/login/index`
    if (code == null || code === "") {
        window.location.href =
            `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${official_appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
        return
    } else {
        return code
    }
}

const app_getCode = () => {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: "weixin",
            "onlyAuthorize": true, // 微信登录仅请求授权认证
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

// 如果是微信小程序端
// #ifdef MP-WEIXIN
const getCode = weixin_getCode
// #endif

// 如果是APP端
// #ifdef APP
const getCode = app_getCode
// #endif

// #ifdef H5
const getCode = Wechat_webpage_authorization_getCode
// #endif


module.exports = {
    getCode,
}